/*
 *接口编写处...
*如果接口需要做Action的权限验证，请在Action上使用属性
*如: [ApiActionPermission("Quality_InboundTest",Enums.ActionPermissionOptions.Search)]
 */
using iMES.Core.Enums;
using iMES.Core.Filters;
using iMES.Entity.DomainModels;
using iMES.Equip.Services;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Yun.New_QualityTest.IServices;
using Yun.New_QualityTest.Entity.DomainModels;
using ZJY.Purchase.Services;

namespace Yun.New_QualityTest.Controllers
{
/// <summary>
/// 获取检验单详情（兼容旧接口）
/// </summary>
/// <param name="id">检验单ID</param>
/// <returns>检验单详细信息</returns>
[HttpGet, Route("GetById")]
[ApiActionPermission("Quality_InboundTest", ActionPermissionOptions.Search)]
public async Task<IActionResult> GetById(Guid id)
{
    // 直接调用已有的GetInspectionOrderDetail方法
    var result = await _service.GetInspectionOrderDetail(id);
    return Json(result);
}

/// <summary>
/// 获取检验单附件列表
/// </summary>
/// <param name="inspectionOrderId">检验单ID</param>
/// <returns>附件列表</returns>
[HttpGet, Route("getAttachments/{inspectionOrderId}")]
[ApiActionPermission("Quality_InboundTest", ActionPermissionOptions.Search)]
public async Task<IActionResult> GetAttachments(Guid inspectionOrderId)
{
    try
    {
        // 假设系统中存在获取附件信息的仓储 - 直接在控制器中查询而不依赖Service
        var attachments = await repository.DbContext.Set<Quality_InboundTest_Attachment>()
            .Where(x => x.InspectionOrderID == inspectionOrderId)
            .Select(a => new
            {
                a.AttachmentID,
                a.AttachmentFileName,
                a.AttachmentFileSize,
                a.AttachmentFilePath,
                a.UploadDate
            })
            .ToListAsync();

        return Json(new
        {
            status = true,
            data = attachments
        });
    }
    catch (Exception ex)
    {
        Console.WriteLine($"获取附件列表异常: {ex.Message}");
        return Json(new { status = false, message = $"获取附件列表失败: {ex.Message}" });
    }
}

/// <summary>
/// 获取检验单明细
/// </summary>
/// <param name="inspectionOrderId">检验单ID</param>
/// <returns>检验明细列表</returns>
[HttpGet]
[Route("getInspectionDetails/{inspectionOrderId}")]
[Route("GetInspectionDetails/{inspectionOrderId}")]
[ApiActionPermission("Quality_InboundTest", ActionPermissionOptions.Search)]
public async Task<IActionResult> GetInspectionDetails(Guid inspectionOrderId)
{
    try
    {
        // 查询指定检验单的明细列表
        var details = await _detailsRepository.FindAsIQueryable(x => x.InspectionOrderID == inspectionOrderId)
            .Select(d => new
            {
                d.InspectionDetailID,
                d.MaterialCode,
                d.MaterialName,
                d.MaterialModel,
                d.UnitName,
                d.Brand,
                d.PurchaseQuantity,
                d.InspectionType,
                d.ReceivedQuantity,
                d.InspectedQuantity,
                d.QualifiedQuantity,
                d.ReturnQuantity,
                d.StockableQuantity,
                d.InspectionDetailRemark
            })
            .ToListAsync();

        return Json(new
        {
            status = true,
            data = details
        });
    }
    catch (Exception ex)
    {
        Console.WriteLine($"获取检验明细异常: {ex.Message}");
        return Json(new { status = false, message = $"获取检验明细失败: {ex.Message}" });
    }
}

/// <summary>
/// 获取检验单操作日志
/// </summary>
/// <param name="inspectionOrderId">检验单ID</param>
/// <returns>操作日志列表</returns>
[HttpGet]
[Route("getOperationLogs/{inspectionOrderId}")]
[Route("GetOperationLogs/{inspectionOrderId}")]
[ApiActionPermission("Quality_InboundTest", ActionPermissionOptions.Search)]
public async Task<IActionResult> GetOperationLogs(Guid inspectionOrderId)
{
    try
    {
        // 查询指定检验单的操作日志
        var logs = await _logsRepository.FindAsIQueryable(x => x.InspectionOrderID == inspectionOrderId)
            .Select(l => new
            {
                l.LogID,
                l.Operator,
                l.OperationTime,
                l.OperationContent
            })
            .OrderByDescending(l => l.OperationTime)
            .ToListAsync();

        return Json(new
        {
            status = true,
            data = logs
        });
    }
    catch (Exception ex)
    {
        Console.WriteLine($"获取操作日志异常: {ex.Message}");
        return Json(new { status = false, message = $"获取操作日志失败: {ex.Message}" });
    }
}

/// <summary>
/// 获取附件信息
/// </summary>
/// <param name="attachmentId">附件ID</param>
/// <returns>附件信息</returns>
[HttpGet]
[Route("getAttachmentInfo/{attachmentId}")]
[Route("GetAttachmentInfo/{attachmentId}")]
[ApiActionPermission("Quality_InboundTest", ActionPermissionOptions.Search)]
public async Task<IActionResult> GetAttachmentInfo(Guid attachmentId)
{
    var result = await _service.GetAttachmentInfo(attachmentId);
    return Json(result);
}

public partial class Quality_InboundTestController
{
    private readonly IQuality_InboundTestService _service;//访问业务代码
    private readonly IHttpContextAccessor _httpContextAccessor;
    private readonly IRepository<Quality_InboundTest_Attachment> _attachmentRepository;

    [ActivatorUtilitiesConstructor]
    public Quality_InboundTestController(
        IQuality_InboundTestService service,
        IHttpContextAccessor httpContextAccessor,
        IRepository<Quality_InboundTest_Attachment> attachmentRepository
    )
    : base(service)
    {
        _service = service;
        _httpContextAccessor = httpContextAccessor;
        _attachmentRepository = attachmentRepository;
    }
}
}